package com.apgblogs.springbootstudy.handler;

import com.apgblogs.springbootstudy.exception.NotFoundException;
import com.apgblogs.springbootstudy.exception.WarningException;
import com.apgblogs.springbootstudy.model.ErrorModel;
import com.apgblogs.springbootstudy.model.ErrorStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @author xiaomianyang
 * @description
 * @date 2019-05-14 23:24
 */
@ControllerAdvice
public class RestExceptionHandler {

    private static Logger logger= LoggerFactory.getLogger(RestExceptionHandler.class);

    /**
     * @description 错误异常处理
     * @author xiaomianyang
     * @date 2019-07-12 13:14
     * @param [e]
     * @return com.apgblogs.springbootstudy.model.ErrorModel
     */
    @ExceptionHandler(value = NotFoundException.class)
    @ResponseBody
    @ResponseStatus
    public ErrorModel handleNotFoundException(NotFoundException e){
        logger.error(e.getMessage(),e);
        return new ErrorModel(e.getMessage(),e.getCode());
    }

    /**
     * @description 警告异常处理
     * @author xiaomianyang
     * @date 2019-07-12 13:14
     * @param [e]
     * @return com.apgblogs.springbootstudy.model.ErrorModel
     */
    @ExceptionHandler(value = WarningException.class)
    @ResponseBody
    @ResponseStatus
    public ErrorModel handleWarningException(WarningException e){
        logger.error(e.getMessage(),e);
        return new ErrorModel(e.getMessage(),e.getCode());
    }

    /**
     * @description 未知错误异常处理
     * @author xiaomianyang
     * @date 2019-07-12 13:14
     * @param [e]
     * @return com.apgblogs.springbootstudy.model.ErrorModel
     */
    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorModel handleGlobalException(Exception e){
        logger.error(e.getMessage(),e);
        return new ErrorModel(ErrorStatus.INTERNAL_SERVER_ERROR);
    }

}
